/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.domain.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;

@Slf4j
public class AutoColumnWidthStyleStrategy implements CellWriteHandler {

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 Row row, Head head, Integer columnIndex, Integer relativeRowIndex,
                                 Boolean isHead) {
        // 在创建单元格前跟踪所有列
        if (writeSheetHolder.getSheet() instanceof org.apache.poi.xssf.streaming.SXSSFSheet) {
            ((org.apache.poi.xssf.streaming.SXSSFSheet) writeSheetHolder.getSheet()).trackAllColumnsForAutoSizing();
        }
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData<?>> cellDataList, Cell cell, Head head,
                                 Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        try {
            // 设置最小列宽
            sheet.setColumnWidth(cell.getColumnIndex(), Math.max(3000, sheet.getColumnWidth(cell.getColumnIndex())));

            // 自动调整列宽（仅对非SXSSFSheet或已跟踪的列）
            if (!(sheet instanceof org.apache.poi.xssf.streaming.SXSSFSheet)) {
                sheet.autoSizeColumn(cell.getColumnIndex());
            }
        } catch (IllegalStateException e) {
            // 忽略SXSSF自动调整列宽的错误
            log.warn("忽略SXSSF自动调整列宽的错误");
        }
    }
}
